package com.servlet.user;

import com.entity.Code;
import com.service.UserService;
import com.utils.JsonUtil;
import com.utils.TimeString;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

/**
 * 根据用户ID来修改用户信息
 * 必选参数：id、username
 * 可选参数：email、description、tel
 */
@WebServlet(name = "UpdateUserById", value = "/UpdateUserById")
public class UpdateUserById extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);

    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        int id = Integer.parseInt(request.getParameter("id"));
        String name= request.getParameter("username");
        String email = request.getParameter("email");
        String avatar = "";
        String description =request.getParameter("description");
        String tel = request.getParameter("tel");
        String update_time =new TimeString().TimeString();

        JsonUtil jsonUtil = new JsonUtil();
        UserService userService = new UserService();
        try {
            int i = userService.updateUserById(id, name, email, avatar, description, tel, update_time);
            if (i==1){
                Code code = new Code();
                code.setMsg("资料修改成功");
                code.setCode("200");
                String s = jsonUtil.JavaToJson(code);
            }

        }catch (Exception e){
            System.out.println("资料修改失败"+e);
            Code code = new Code();
            code.setCode("403");
            code.setMsg("资料修改失败，请稍后再试");
            String s = jsonUtil.JavaToJson(code);
            response.getWriter().print(s);
        }
    }
}
